#!/bin/env python
#coding:utf-8

import logging
logger = logging.getLogger(__name__)

from django.shortcuts import render
from django.shortcuts import  HttpResponse
import json
from .qiniu import apiSearch
from .models import BusinessGroup, TeamUser, PackageName

from grafanaCallBack.conf import setting

def callBack(request):
    nginxAccessRepoName = 'nginx_access_log'     #Nginx Access七牛云日志库名称
    applicationRepoName = 'application_log'      #应用程序七牛云日志库名称

    if request.method == "POST":
        for k in request.POST:
            logging.info('POST提交过来的参数列表为：'+str(k)+'===>'+str(request.POST.get(k)))
            # print 'POST提交过来的参数列表为：'+str(k)+'===>'+str(request.POST.get(k))
        postDataObj = request.body
        logging.info('request.body data is:' + str(postDataObj))
        postDataObj = postDataObj.replace("'",'"')  #在JSON中，标准语法中，不支持单引号，属性或者属性值，都必须是双引号括起来的。
        postDataObj = json.loads(postDataObj.decode('utf-8'))
        for k,v in postDataObj.items():
            logger.info('POST提交的参数为:'+str(k)+'===>'+str(v))

        if postDataObj['state'] == 'ok':    #报警恢复
            pass
        else:   #产生报警
            packageAbsLogPath = postDataObj.get('message')  #获取报警应用
            if packageAbsLogPath == None:
                logger.info('传入的应用错误，请检查！！！')
            else:
                team_leaderUser = []        #获取应用的报警联系人(即应用直接关联的用户邮件地址、以及应用关联用户组下用户的邮件地址)
                team_user = []
                print ('packageAbsLogPath is:', packageAbsLogPath)
                # 获取应用包直接关联的用户列表
                for i in PackageName.objects.get(name=packageAbsLogPath).team_user.all():
                    team_leaderUser.append(i.email)
                # 获取应用包关联组下面的用户列表
                business_group = PackageName.objects.get(name=packageAbsLogPath).business_group.all()
                for i in business_group:
                    tmpTeam_user = BusinessGroup.objects.get(id=i.id).teamuser_set.all()
                    print ('tmpTeam_user is:', type(tmpTeam_user), tmpTeam_user, list(tmpTeam_user))
                    for j in tmpTeam_user:
                        if j.is_leader == True:
                            team_leaderUser.append(j.email)
                        else:
                            team_user.append(j.emall)
                print ('team_leaderUser is:', team_leaderUser)
                print ('team_user is:', team_user)
                subject = '[Alerting] %s 产生错误日志' % packageAbsLogPath

                if packageAbsLogPath.endswith('yunlai.cn.log'):
                    apiSearch.callBack(packageAbsLogPath, nginxAccessRepoName, subject, team_leaderUser, team_user)
                elif packageAbsLogPath.endswith('.log'):
                    apiSearch.callBack(packageAbsLogPath, applicationRepoName, subject, team_leaderUser, team_user)
                else:
                    logger.info('传入的应用错误，请检查！！！')

    return HttpResponse('<h1>Grafana Call Back Page</h1>')
